package br.com.ema.maze.agents;

import java.util.ArrayList;
import java.util.List;

import br.com.ema.maze.components.MazeSpace;
import br.com.ema.maze.components.MazeWall;
/**
 * @author Emanuel Cruz Rodrigues -> emanuelcruzrodrigues@gmail.com
 *
 */
public class WallPassageAllowerAgent extends Thread {
	
	private int maxInterval;
	private List<MazeWall> walls = new ArrayList<MazeWall>();
	private boolean running = false;
	private boolean alive = true;
	
	
	public WallPassageAllowerAgent(int maxInterval) {
		this.maxInterval = maxInterval;
		walls = new ArrayList<MazeWall>();
	}
	
	
	public void addWall(MazeSpace space) {
		this.addWall((MazeWall) space.getDecoration());
	}

	public void addWall(MazeWall wall){
			walls.add(wall);
	}
	
	
	@Override
	public void run() {
		while(alive){
			try {
				Thread.sleep(getNextInterval());
				if (running){
					if (walls.size() > 0){
						MazeWall wall = walls.get(getNextWallIndex());
						wall.setAllowsPassage(!wall.allowsPassage());
					}
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private int getNextInterval(){
		return (int)(Math.random() * maxInterval);
	}
	
	private int getNextWallIndex(){
		return (int)(Math.random() * walls.size());
	}
	
	public void kill(){
		alive = false;
	}
	
	public void stopAnimation(){
		this.running = false;
	}
	
	public void animate() {
		this.running = true;
		if (! isAlive()){
			start();
		}
	}


}
